package service

import (
	"context"
	"errors"

	"github.com/google/uuid"
	"github.com/samber/do/v2"

	"gitee.com/monkeyPP/happy-mall/services/userservice/internal/domain/entity"
	"gitee.com/monkeyPP/happy-mall/services/userservice/internal/domain/repository"
)

type UserService interface {
	AddUser(ctx context.Context, user *entity.User) (*entity.User, error)
	GetUser(ctx context.Context, user *entity.User) (*entity.User, error)
}

type UserServiceImpl struct {
	userRepo repository.User
}

func NewUserService(i do.Injector) (UserService, error) {
	userRepo := do.MustInvoke[repository.User](i)
	return &UserServiceImpl{
		userRepo: userRepo,
	}, nil
}

func (s *UserServiceImpl) AddUser(ctx context.Context, user *entity.User) (*entity.User, error) {
	if user == nil {
		return nil, errors.New("user is nil")
	}

	existUser, err := s.userRepo.Get(ctx, user)
	if err != nil {
		return nil, err
	}

	if existUser != nil {
		return nil, errors.New("user is exist")
	}

	// 设置 user.ID
	user.ID = uuid.New().String()
	newUser, err := s.userRepo.Add(ctx, user)
	if err != nil {
		return nil, err
	}
	return newUser, nil
}

func (s *UserServiceImpl) GetUser(ctx context.Context, user *entity.User) (*entity.User, error) {
	if user == nil {
		return nil, errors.New("user is nil")
	}

	return s.userRepo.Get(ctx, user)
}
